// 井字棋

import React, { useEffect, useState } from 'react';
import styles from './index.less';

const TicTacToe: React.FC = () => {
  const lines = [
    //胜利的格子
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
  ];

  const [status, setStatus] = useState<string>('X'); // 当前执棋者
  const [squares, setSquares] = useState<Array<any>>(Array(9).fill(null)); // 占领格子领地的执棋者
  const [history, setHistory] = useState<Array<any>>([]); // 历史记录
  const [winner, setWinner] = useState<string>(''); // 胜利者

  useEffect(()=>{//随机选取第一步执棋者
    const firster = Math.random()>0.5 ? 'X' : 'O'
    setStatus(firster)
  },[])

  //点击格子
  const clickSquare = (index: number) => {
    //是否已点击过改格子或者已有获胜者
    if (squares[index] || winner) {
      return;
    }

    let resArr = squares;
    resArr[index] = status;
    setSquares(()=>{return [...resArr]});

    let historyArr = history;
    historyArr.push({
      order: history.length>0?history[history.length-1].order+1:1, // 下子的顺序
      index: index, // 下子的格子
      owner: status, // 下子的操作人
    });
    setHistory(()=>{return [...historyArr]});

    setStatus(status==='X' ? 'O' : 'X')

    // 判断胜出者,至少有一个人下到第三步
    if (historyArr.length < 5) {
      return;
    }
    for (let i = 0; i < lines.length; i++) {
      const [a, b, c] = lines[i];
      console.log('[a,b,c]', i, [a, b, c], resArr[a], resArr[b], resArr[c]);

      if (resArr[a] && resArr[a] === resArr[b] && resArr[a] === resArr[c]) {
        //获胜了
        setWinner(() => resArr[a]);
        return;
      }
    }

    if(history.length>6){
      let delHistory = history[0]
      squares[delHistory.index] = ''
      historyArr.shift()
      setHistory(()=>{return [...historyArr]})
    }
  };

  // 历史回退到某一步
  const goBack = (index: number) => {
    let historyArr = history.slice(0, index + 1);
    setHistory(()=>{return [...historyArr]});
    // 初始化
    setWinner('');
    let squaresArr: Array<any> = Array(9).fill(null);
    historyArr.forEach((item) => {
      squaresArr[item.index] = item.owner;
    });
    setSquares(squaresArr);
    setStatus(historyArr[historyArr.length-1].status==='X'?'O':'X')
  };

  const Square = (index: number) => {
    return (
      <span className={styles['square']} onClick={() => clickSquare(index)}>
        {squares[index]}
      </span>
    );
  };

  const Board = () => {
    return (
      <div
        className={`${styles['game-board']} ${
          winner ? styles['success-bg'] : ''
        }`}
      >
        <div className={styles['board-row']}>
          {Square(0)}
          {Square(1)}
          {Square(2)}
        </div>
        <div className={styles['board-row']}>
          {Square(3)}
          {Square(4)}
          {Square(5)}
        </div>
        <div className={styles['board-row']}>
          {Square(6)}
          {Square(7)}
          {Square(8)}
        </div>
      </div>
    );
  };

  const GameInfo = () => {
    return (
      <div className={styles['game-info']}>
        {history.map((item, index) => {
          const desc = `第${item.order}步: ${item.owner}下在了第${
            item.index + 1
          } 格 `;
          return (
            <div key={item.order} className={styles['history']}>
              {desc}
              <span onClick={() => goBack(index)} className={styles['btn']}>
                回到该步
              </span>
            </div>
          );
        })}
      </div>
    );
  };

  return (
    <div className={styles['game']}>
      <div className={`${styles['status']} ${winner ? styles['success-bg'] : ''}`} >
        {winner ? 'winner is ' + winner : 'Next player : ' + status}
      </div>
      <div className={styles['rule']}>
        <p>说明：场上最多只能放置3个棋子，多了之后，从第一步开始清空;</p>
        <p>胜利条件：连续三格都是相同的棋子;</p>
      </div>
      <Board />
      {history.length>0?<GameInfo />:''}
    </div>
  );
};

export default TicTacToe;
